﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CPPEI.Net.TCP
{
    /// <summary>
    /// 重新连接的线程
    /// </summary>
    public class TCPReconnectThread
    {
        private Thread _thread;
        private bool _isRunning;
        private EventWaitHandle _waitHandle;

        private TCPClient _client;

        public TCPReconnectThread(TCPClient client)
        {
            _client = client;
        }

        public void Start()
        {
            if (_isRunning)
            {
                return;
            }
            Debug.WriteLine("重连线程开启");
            _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
            _thread = new Thread(Running);
            this._thread.Name = "recThread" + Guid.NewGuid().ToString("N");
            _isRunning = true;
            _thread.Start();
        }

        public void Stop()
        {
            _isRunning = false;
            _waitHandle.WaitOne();
        }

        private void Running()
        {
            while (_isRunning)
            {
                try
                {
                    _client.Reconnect();
                    _isRunning = false;
                    _waitHandle.Set();
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(string.Format("重新连接失败,ex:{0}", ex));
                    Thread.Sleep(5000);
                }
            }
            _waitHandle.WaitOne();
            _waitHandle = null;
            Debug.WriteLine("重连线程关闭");
        }
    }
}
